<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>11_节流-尾部执行控制</title>
</head>
<body>
  
  <button>按钮</button>

  <input type="text">

  <script>
    function throttle(fn, interval, { leading = false, trailing = true } ) {
      let startTime = 0
      let timer = null
      const _throttle = function (...args) {
        const nowDate = new Date().getTime()
        if (!leading && startTime === 0) {
          startTime = nowDate
        }

        const waitTimeFlag = (nowDate - startTime) >= interval
        if (waitTimeFlag) {
          if (timer) clearTimeout(timer)
          fn.apply(this, args)
          startTime = nowDate
          timer = null
          return
        }

        if (trailing && !timer) {
          timer = setTimeout(() => {
            fn.apply(this, args)
            startTime = new Date().getTime()
            timer = null
          }, interval)
        }
      }
      return _throttle
    }

    const inputEl = document.querySelector("input")
    let counter = 1
    inputEl.oninput = throttle(function (event) {
      console.log(`发送了第${counter++}次网络请求`, this.value, event)
    }, 1000, { trailing: true })

  </script>

</body>
</html>